package com.znzz.course.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.znzz.course.R;
import com.znzz.course.entity.Student;
import com.znzz.course.util.ConnByHttp;
import com.znzz.course.util.db.StudentDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 学号登陆模块
 */
public class LoginStudentActivity extends AppCompatActivity {

    private Button buttonLogin;  //登陆按钮
    private EditText editTextStudent, editTextPas;  //输入文本
    private TextView tvOtherLogin;  //其他登陆方式（电话
    Handler handler;
    //本地文本，保存用户基本信息
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    //设置全局student
    public Student student;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_student);
        initView();
        //将输入的信息保存到本地数据库，实现自动登陆
        sharedPreferences = getSharedPreferences("studentInfo", 0);
        String studentId = sharedPreferences.getString("studentId", "");
        String password = sharedPreferences.getString("password", "");
        editTextStudent.setText(studentId);
        editTextPas.setText(password);

        commonLogin();
        //其他登陆方式跳转
        tvOtherLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginStudentActivity.this, LoginActivity.class));
            }
        });

        /**
         * 第一次登陆会调用该方法
         * //异步处理核心，子主线程实现通信，接收传回来的信息进行处理---》返回的是JSONObject数据类型
         */
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        //将返回的content数据分析封装到Student类中--》JOSNObject对象
                        String content = msg.obj.toString();
                        JSONObject jsonObject;
                        String result = "";
                        //保存学生信息到本地数据库中
                        StudentDao studentDao = new StudentDao(LoginStudentActivity.this);
                        if (studentDao.loadData() != null) {
                            studentDao.deleteStudent();
                        }
                        try {
                            jsonObject = new JSONObject(content);
                            result = jsonObject.getString("result");
                            String major = jsonObject.getString("major");
                            String collage = jsonObject.getString("collage");
                            jsonObject = new JSONObject(jsonObject.getString("student"));
                            //将传递的数据封装到student对象中
                            student = new Student();
                            student.setStudentId(jsonObject.getString("studentId"));
                            student.setName(jsonObject.getString("name"));
                            student.setPassword(jsonObject.getString("password"));
                            student.setSex(jsonObject.getString("sex"));
                            student.setClazzId(jsonObject.getString("clazzId"));
                            student.setMajor(major);
                            student.setPhone(jsonObject.getString("phone"));
                            student.setCollage(collage);
//                            System.out.println("student="+student.getName().toString());
                            //将学号和密码保存本地，实现自动登陆
                            setUserAccount(student.getStudentId(), student.getPassword());
                            //保存本地数据库，下次直接获取该学生的信息
                            studentDao.saveData(student);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (result.equals("T")) {
                            Intent intent = new Intent(LoginStudentActivity.this, MainActivity.class);
                            intent.putExtra("studentId", student.getStudentId());
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(LoginStudentActivity.this, "登陆失败", Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        };
        //学号登陆的方式，访问自己搭建的服务器，查询数据库是否存在该学生，没有返回F有返回T，实现登陆，同时拉取学生的信息
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //服务器地址及对应的实现方法
                String url = "http://192.168.92.1:8123/courseServer/doLoginByStudentId";
                String studentId = editTextStudent.getText().toString();
                String password = editTextPas.getText().toString();
                url = url + "?studentId=" + studentId + "&password=" + password;
                //启动子线程
                ConnByHttp connByHttp = new ConnByHttp(url, handler);
                connByHttp.start();
            }
        });
    }

    //获取对应的R.id 对象
    public void initView() {
        buttonLogin = findViewById(R.id.buttonLogin);
        editTextPas = findViewById(R.id.editTextPas);
        editTextStudent = findViewById(R.id.editTextStudent);
        tvOtherLogin = findViewById(R.id.tv_other_login);
    }

    /**
     * 将用户信息暂时存到SharePreference中，因为SharePreference只能存储普通类型数据，
     * 所以才存储用户信息时，将对象转换为JSON字符串后，再将JSON字符串保存。
     */
    private void setUserAccount(String studentId, String password) {
        editor = sharedPreferences.edit();
        editor.putString("studentId", studentId);
        editor.putString("password", password);
        // 完成提交
        editor.apply();
    }

    //自动登陆判断，跳转到主页面
    public void commonLogin() {
        String studentId = editTextStudent.getText().toString();
        String password = editTextPas.getText().toString();
        if (studentId.length() != 0 && password.length() != 0) {
            //页面跳转，传递学生学号
            Intent intent = new Intent(LoginStudentActivity.this, MainActivity.class);
            intent.putExtra("studentId", studentId);
            startActivity(intent);
            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}